package com.hnevc.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;

import javax.security.auth.login.LoginException;

/**
 * Created by Administrator on 2017/12/1.
 */

public class MyService  extends Service{
    private static final String TAG = "MyService";
    private MediaPlayer mediaPlayer;

    public MyService() {

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        mediaPlayer = MediaPlayer.create(this,R.raw.qinglang);
        Log.e(TAG, "onBind: " );
        return new MyBinder();

    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind: " );
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate: " );
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: " );
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy: " );
    }


    class MyBinder extends Binder{
        //定义方法，供Activity调用
        public void call(String command){
            Log.e(TAG, "call: "+command );
            if(command.equals("PLAY")){
                play();
            }
            if (command.equals("PAUSE")){
                pause();

            }
            if (command.equals("STOP")){
                stop();
            }
        }

    }

    private void stop() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            //停止
            Log.e(TAG, "stop: ");
        }
    }

    private void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            //暂停
            Log.e(TAG, "pause: ");

        }
    }

    public void play() {
        mediaPlayer = MediaPlayer.create(MyService.this, R.raw.qinglang);
        if(!mediaPlayer.isPlaying()){
        mediaPlayer.start();
        Log.e(TAG, "call: "+"正在播放" );
    }else {
            Log.e(TAG, "play: "+"已经播放了" );
        }
}}
